from threading import Lock, Thread
from time import sleep


def fun1(name):
    lock1.acquire()
    print(f'{name}拿到了lock1')
    sleep(1)  # 注意一定要拿到一个锁之后开始阻塞，否则两把锁都拿到后再开始阻塞，拿到两把锁的线程不需要等待，执行完之后另一个线程也能拿到两把锁
    lock2.acquire()
    print(f'{name}拿到了lock2')

    lock2.release()
    print(f'{name}归还了lock1')
    lock1.release()
    print(f'{name}归还了lock2')


def fun2(name):
    lock2.acquire()
    print(f'{name}拿到了lock2')
    sleep(1)
    lock1.acquire()
    print(f'{name}拿到了lock1')

    lock1.release()
    print(f'{name}归还了lock1')
    lock2.release()
    print(f'{name}归还了lock2')


if __name__ == '__main__':
    lock1 = Lock()
    lock2: Lock = Lock()
    t1 = Thread(target=fun1, args=('t1',))
    t2 = Thread(target=fun2, args=('t2',))
    t1.start()
    t2.start()
